<%@ page contentType="application/json;charset=utf-8" language="java"
	import="com.zz.comframe.*"%>
<%@page import="treemap.zz.json.*"%>
<%@page import="java.util.*"%>
<%@page import="com.zz.comframe.properties.PropertiesPool"%>

<%
	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8");

	//select控件型column列表
	//String[] selcols = ["cellattr","editoptions","editrules","formoptions","formatoptions","searchoptions","template","unformat"];
	CommonDataProcesser dp = new CommonDataProcesser();


	//////////////////////////////////////////JQGRID setup//////////////////////////////////////////
	String sql1 = PropertiesPool.getCommonpro("SQL_SELECT_GRIDHEADER")+" where grid='per_grid1' "; //获得gridheaders
	String sql2 = PropertiesPool.getCommonpro("SQL_SELECT_TERMTAB");
	JSONArray colarr = dp.getObjectListAll(sql1);
	JSONArray termarr = dp.getObjectListAll(sql2);
	for(int i=0; i<colarr.length(); i++){	//为课程（类型）字段填充数据
		if(colarr.getJSONObject(i).getString("name")!=null && colarr.getJSONObject(i).getString("name").equalsIgnoreCase("col2")){
			JSONArray cosarr = dp.getObjectListAll(PropertiesPool.getCommonpro("SQL_SELECT_COSTAB"));
			JSONObject cosjo = new JSONObject("{value:{\"\":\"全部\"}}");
			//cosjo.put("value",new JSONObject("{\"\":\"全部\"}"));
			for(int j=0; j<cosarr.length(); j++)
				cosjo.getJSONObject("value").put(cosarr.getJSONObject(j).getString("cosid"), cosarr.getJSONObject(j).getString("cosname"));
			colarr.getJSONObject(i).put("editoptions",cosjo );//'{\"value\":{\"1\":\"基本课程\",\"2\":\"深化课程\"}}'
			//cosjo.getJSONObject("value").remove("");
			colarr.getJSONObject(i).put("searchoptions", cosjo);//'{\"value\":{\"1\":\"基本课程\",\"2\":\"深化课程\"}}'
			break;
		}
	}

	String str = "{ \"columns\":" + colarr + ",\"terms\":" + termarr + "}";
	str = str.toLowerCase().replaceAll("\"true\"","true").replaceAll("\"false\"","false");
	str = str.replaceAll("\"cid\"","\"id\"").replaceAll("\"ckey\"","\"key\"");
	////////////////////////////////////////////////////////////////////////////////////////////////
	//width必须是数值，拼装数据时要分出类型

%>
jQuery(document).ready(function() {
/**
 * 解析columnmodle，将相应参数由字符串转换为对象
 * 如：'{value:{1:\"One\",2:\"Two\"}}' to {value:{1:"One",2:"Two"}}
 */
	function getcolumnmodlesobj(jsonstring){
		var obj_attr_arr_name = ["cellattr","editoptions","editrules","formoptions","formatoptions","searchoptions","template","unformat"];
		var jo = $.zzJSON.parseJSON(jsonstring);
		if(jo && jo.columns &&jo.columns.length>0){
			$.each(obj_attr_arr_name,function(i,attrname){
				$.each(jo.columns, function(n, column){
					if($(column).attr(attrname)!=null&&(typeof $(column).attr(attrname) == "string") )
						$(jo.columns[n]).attr(attrname,$.zzJSON.parseJSON($(column).attr(attrname)));
				});
			});
		}
		return jo;
	}
	
	//object格式不能解析  .parseJSON( '{ "columns": [{"formatter":jQuery.parseJSON("{\"date\":{\"mask\":\"y-m-d\"}}"),"index":"col9","align":"right","sorttype":"date","width":100,"tab":"perinfo_jqg","label":" 生日","id":"8"}]}');

	//var json =getcolumnmodlesobj('{ "columns": [{"index":"col1","width":80,"searchtype":"string","id":"0","label":"学号","name":"col1"}'+
	//',{"index":"col2","searchoptions":{\"value\":{\"男\":\"男\",\"女\":\"女\"}},"stype":"select","label":"类别","name":"col2"}]}'); 
	var json = getcolumnmodlesobj('<%=str%>');
  	var combo = $( "select[name=termselect]");//"select[name=termcombo]" );
	$("select[name=termselect]").attr("value","aaasd");

	$.each(json.terms,function(i,term){
		$("<option name="+i+"/>").appendTo("select[name='termselect']");//添加下拉框的option
		var d = new Date(term.value);
		$("select[name='termselect'] option[name="+i+"]")[0].text = term.value;//d.getMonth()>6 ? d.getFullYear()+" 下半年" :  d.getFullYear()+" 上半年" ;
		$("select[name='termselect'] option[name="+i+"]")[0].value = term.value;
	});
	
	//var curr_trem = combo[0].value;//json.terms[0].value;
	var coltypes = {"id":"string"};
    $.each($(json.columns),function(i,col){
        $(coltypes).attr(col.name,col.sorttype) ;
    });
    coltypes = {"extpar":$.zzJSON.toJSONString(coltypes)};
    //coltypes = $.zzJSON.parseJSON("{"+coltypes.substr(1,coltypes.length)+"}");   	
	var lastSel = null;
	jQuery("#grid1").jqGrid({
		//url : './jsp/dycolumn-list.jsp',
		url: './getlist.do',
		// data: json.rows,
		datatype : "json",// "local",
		jsonReader : {
			// root : "rows",
			page : "curpage", // 当前页
			records : "totalrecords", // 总记录数
			repeatitems : false,
			total : function(obj) { // 总页数
				var rownum = jQuery("#grid1").jqGrid("getGridParam", "rowNum");
				return Math.round(parseInt(obj.totalrecords) / rownum + 0.5);
			},
			id : "col0"
		},
		gridview : true,
		colModel : json.columns, // 有大小写问题，column中name与data中field必须一致
		cmTemplate : {
			sortable : false
		}, // 相当于default，覆盖原column的default，column指定值不会被覆盖
		autowidth : true,
		mtype : 'post',
		rowNum : 30,
		rowList : [10, 30, 50],
		pager : '#prowed1',
		sortname : 'col1',
		viewrecords : true,
		sortorder : "asc",
		editurl : "save.do",
		postData : {"grid":"per_grid1","term":combo[0].value},
		inlineData : {"term":combo[0].value},
		toolbar: [true,"top"] ,
		subGrid : true,
		subGridRowExpanded : function(subgridid, id) {
			var data = {
				subgrid : subgridid,
				id : id
			};
			if (false){//id && id!='') {
				var anm = '';
				anm = anm.split(",");
				var rd = jQuery(this).jqGrid('getRowData', id);
				
				if (rd) {
					$.each(json.columns,function(i,col){
						data[i] = [col.name,col.label,rd[col.name]];
					});
					//$(data).attr(rd);
				}
			}
			$("#" + jQuery.jgrid.jqID(subgridid)).load('getdetail.do',data);//getdetail.do', data);
		},
		onSelectRow: function(id){
		}
	});

	$("#grid1").jqGrid('navGrid', "#prowed1", {
				edit : false,
				add : false,
				del : true,
				save : true,
				searchtext : "Advance Search",
				searchicon : "ui-icon-note"
			}, {}, {}, {}, {
				multipleSearch : true,
				multipleGroup : false,
				showQuery : false
			});
	$("#grid1").jqGrid('inlineNav', "#prowed1", {
				edit : true, add : true, save : true, cancel : true,
				editParams : {
					extraparam : coltypes,
					keys : false,
					successfunc : function(resp) {
						var result = false;
						var rejson = $.zzJSON.parseJSON(resp.responseText);
						if (rejson && rejson.success) {
							result = true;
							$('#grid1').trigger('reloadGrid');
						} else
							alert(rejson && rejson.msg ? rejson.msg : "数据错误，无法保存");
						return result;
					},
					url : null,
					aftersavefunc : function() {
						return true;
					},
					errorfunc : function() {
						// alert("errorfunc");
						return true;
					},
					afterrestorefunc : function() {
						//alert("afterrestorefunc");
						return true;
					},
					restoreAfterError : false,
					mtype : "POST"
				}

			}, {});
	$("#grid1").jqGrid('navButtonAdd', "#prowed1", {
		caption : "",
		title : "快速定位",
		buttonicon : "ui-icon-search",
		position : "first",
		onClickButton : function() {
			var trow = $("tr.ui-search-toolbar", $("#grid1")[0].hDiv)
			if (trow && trow.length > 0) {
				var sgrid = $("#grid1")[0];
				sgrid.clearToolbar();
				sgrid.toggleToolbar();
			} else
				jQuery("#grid1").jqGrid('filterToolbar', {
					beforeSearch : function() {
						$t = this;
						// {"groupOp":"AND","rules":[{"field":"col1","op":"cn","data":"23"}]}
						var obj = $.zzJSON.parseJSON($t.p.postData.filters);
						$.each(obj.rules, function(i, rule) {
							$.each($t.p.colModel, function(j, col) {
								if (col.name == rule.field) {
									var coltype = col.searchtype
											? col.searchtype
											: col.sorttype;
									if ('string,text,date'.indexOf(coltype) >= 0) { // is not number
										rule.data = rule.data && rule.data.trim() != "" ? "'"
												+ rule.data.trim() + "'" : "";
									}
								}
							});
						});
						$.extend($t.p.postData, {
									filters : $.zzJSON.toJSONString(obj)
								});
						//alert($t.p.postData.filters);
					},
					stringResult : true,
					searchOnEnter : true,
					defaultSearch : "cn"
				});

			resizefn();
		}
	});
	
  	var x = $("#t_grid1").append("&nbsp;&nbsp<span>  学期：</span>",combo,"<span>&nbsp;&nbsp;&nbsp;&nbsp;</span>").height(28);
  	$("#t_grid1").addClass('zz-toolbar');

  	combo.show();	//解出控件隐藏状态
	combo.change(function(){
       $('#grid1').jqGrid("setGridParam",{postData:{"term":combo[0].value}}).trigger("reloadGrid",[{page:1}])
       //alert($("#selectTest").attr("name"));
       //$("a").attr("href","xx.html");
       //alert($("#selectTest").val());
      // alert($("#selectTest option[@selected]").text());
       //$("#selectTest").attr("value", "2");

	});

	var resizefn = function(){
		jQuery("#grid1").jqGrid('setGridHeight',
				$("#tabs").innerHeight() - 120 - 50); // 50是edit按钮高度
	}
	resizefn();
	var datePick = function(elem) {
		jQuery(elem).datepicker();
	}
	
});